package com.itheima.axios;

import com.alibaba.fastjson.JSON;
import com.itheima.pojo.Person;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/*
 *   json格式: 前后端数据传递的主流格式(替代了XML)
 *       1). XML一个是作为配置文件
 *       2). XML还可以作为数据传递的规范格式(被json替代)
 * */
@WebServlet("/Ajax2Servlet")
public class Ajax2Servlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 接收请求
        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username + "," + password);
        System.out.println("登录成功");

        //2. 业务处理

        //3. 响应数据
        ArrayList<Person> list = new ArrayList<>();
        Person p1 = new Person("高圆圆", 18);
        Person p2 = new Person("贾静雯", 19);
        Person p3 = new Person("袁洁莹", 20);
        list.add(p1);
        list.add(p2);
        list.add(p3);
        //TODO; javaBean -> json
     /*   String content="[";
        for (int i = 0; i < list.size(); i++) {
            Person p = list.get(i);
            if(i == list.size() - 1){
                content+=p.toJson();
            }else{
                content+=p.toJson()+",";
            }
        }
        content+="]";

        System.out.println(content);*/

        String content = JSON.toJSONString(list);
        System.out.println(content);

        response.setContentType("text/html;charset=utf-8");
        //响应数据变成json
        response.getWriter().print(content);
    }

}